<?php

namespace App\Http\Controllers\Api\CMS;

use App\Http\Requests\CategoryRequest;
use App\Models\CMS\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryResource;

class CategoryController extends Controller
{
    /**
     * 显示所有数据
     * @return array
     */
    public function index()
    {
        $category = Category::query()->orderByDesc('id')->get();
        return $this->category($category);
    }

    /**
     * @param $categories
     * @param int $parent_id
     * @return array
     */
    function category($categories, $parent_id = 0)
    {
        $arr = array();
        foreach ($categories as $category => $values) {
            if ($values['parent_id'] == $parent_id) {
                if (count($this->category($categories, $values['id']))) {
                    $values['children'] = $this->category($categories, $values['id']);
                }
                $arr[] = $values;
            }
        }
        return $arr;
    }

    /**
     * 添加
     * @param CategoryRequest $request
     * @return CategoryResource
     */
    public function store(CategoryRequest $request)
    {

        $model = new Category();
        $model->name = $request->get('name','');
        $model->parent_id = $request->get('parent_id',0);
        $parent = $request->parent_id;
        if ($parent > 0) {
            $category = Category::query()->where('id', $parent)->first();
            $parentFullPath = $category->full_path;
            $model->full_path = $parentFullPath . '/' . $model->name;
        } else {
            $model->full_path = '/' . $model->name;
        }
        if ($model->save()) {
            return new CategoryResource($model);
        } else {
            return response()->json(['message'=>'添加失败，请核对信息'], 462);
        }
    }

    /**
     * 获得一条数据
     * @param $cateId
     * @return CategoryResource
     */
    public function show($cateId)
    {
        $model = $this->findModel($cateId);

        return new CategoryResource($model);
    }

    /**
     * 获得model
     * @param $cateId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|null|object
     */
    public function findModel($id)
    {
        $childModel = Category::query()->findOrFail($id);
        return $childModel;
    }

    /**
     * 编辑
     * @param CategoryRequest $request
     * @param $cateId
     * @return CategoryResource
     */
    public function update(CategoryRequest $request, $cateId)
    {
        $model = Category::query()->findOrFail($cateId);
        $model->name = $request->name;
        $model->parent_id = $request->parent_id;
        $parent = $request->parent_id;
        if ($parent > 0) {
            $category = Category::query()->where('id', $request->parent_id)->first();
            $parentFullPath = $category->full_path;
            $model->full_path = $parentFullPath . '/' . $model->name;
        } else {
            $model->full_path = '/' . $model->name;
        }
        $model->save();
        return new CategoryResource($model);
    }

    /**
     * @param $cateId
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy($cateId)
    {

        $model = Category::query()->where('id', $cateId)->first();
        $model->delete();
        $this->deleteSonCategory($cateId);
        return response()->json(['state' => 'success']);

    }

    /**
     * 查询该分类下所有文章数量
     * @param $id
     * @return int
     */
    protected function checkCategoryCanDelete($id)
    {
        //dd($this->getCategoryChild($id));
        return Content::query()->whereIn('category_id', $this->getCategoryChild($id))->count();
    }

    /**
     * 递归获取所有的分类子集
     * @param $id
     * @return array
     */
    protected function getCategoryChild($id)
    {
        $arr = [];
        $arr[] = $id;
        $categorys = Category::query()->where('parent_id', $id)->select('id')->get();
        if ($categorys) {
            foreach ($categorys as $item) {
                $arr[] = $item->id;
                //return $item->id;
                $arr = array_unique(array_merge($arr, $this->getCategoryChild($item->id)));
            }
        }
        return $arr;
    }

    /**
     * 删除该栏目下的所有子栏目
     * @param $id
     */
    public function deleteSonCategory($id)
    {
        $models = Category::query()->where('parent_id', $id)->get();
        if ($models) {
            foreach ($models as $model) {
                $this->deleteSonCategory($model->id);
                $model->delete();
            }
        }
    }

//    public function checkContent($cateId)
//    {
//        /* $model = $this->findModel($cateId);
//         $contents = $model->contents;
//         if ($contents->count()) {
//             return response()->json(['state' => '该分类下有内容，是否继续删除']);
//         } else {
//             return response()->json(['state' => 'success']);
//         }*/
//
//        if ($allModel = Category::query()->where('parent_id', $cateId)->first()) {
//            return response()->json(['state' => '该栏目下有内容，无法删除']);
//        } else {
//            return response()->json(['state' => 'success']);
//        }
//    }
}
